<?php

class Connection {

    private $user = "postgres";
    private $password = "postgres";
    private $db = "spatial_data";
    private $host = "localhost";
    private $port = "5432";
    private $connection;
    private static $instance;

    public static function getInstance() {
        if (!isset(self::$instance))
            self::$instance = new Connection();
        return self::$instance;
    }

    private function __construct() {
        $this->openConnection();
    }

    public function __destruct() {
        $this->closeConnection();
    }

    private function openConnection() {

        try {
            $this->connection = pg_connect("host=$this->host user=$this->user password=$this->password dbname=$this->db port=$this->port");

            if (pg_connection_status($this->connection) !== 0) {
                throw new Exception("erroconnection");
            }
            
        } catch (Exception $erro) {
            echo $erro->getMessage();
            exit;
        }
    }
    
    
    private function closeConnection() {
        return pg_connection_status($this->connection) === 0 ? (!pg_connection_busy($this->connection) ? @pg_close($this->connection) : false) : false;
    }

    public function executeSQL($sql) {
        $msgErro = '';

        if (pg_connection_status($this->connection) === 0) {
            if (strpos(strtoupper($sql), "ELETE") != 1) {
                $result = pg_query($this->connection, $sql);
                return $result;

            } else {
                $this->executeSQLDelete($sql);
            }
        } else {
            $msgErro = 'Ocorreu um erro [' . pg_last_error() . ']';
            throw new Exception($msgErro);
            exit;
        }
    }

    //------------------------------------------
    public function executeSQLDelete($sql) {
        pg_send_query($this->connection, $sql);
        $res1 = pg_get_result($this->connection);

        if (pg_result_error_field($res1, PGSQL_DIAG_SQLSTATE) != 23503) {
            //echo "true";
            return true;
        } else {
            //echo "false";
            return false;
        }

        $dirCompleto = $_SERVER['REQUEST_URI'];
        $VetDir = explode("/", $dirCompleto);

        if ($VetDir[2] != 'MAG') {
            echo $msg;
            die();
        }
    }

}

?>
